package com.thinkgem.jeesite.modules.weixin.checkrequestisfromwechat;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Objects;

/**
 * Created by yangrui on 2018/4/1.
 */
@Slf4j
public class CheckUtils {
    /**
     * 自己在微信里边填写的token
     */
    private static final String token = "yang01rui0118203650478";

    public static boolean checkSignature(CheckRequestFromWeChatEntity entity) {
        log.debug("准备验证请求来至微信：{}", entity.toString());
        String[] arr = new String[]{token, entity.getTimestamp(), entity.getNonce()};
        // 排序
        Arrays.sort(arr);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        // sha1加密
        String sha1 = convertToSHA1(content.toString());
        log.debug("signature：{}", entity.getSignature().toUpperCase());
        log.debug("加密后的密文：{}", sha1);
        return Objects.equals(entity.getSignature().toUpperCase(), sha1);
    }

    public static String convertToSHA1(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] digest = md.digest(str.getBytes());
            return byteToStr(digest);
        } catch (Exception e) {
            log.info("SHA1 加密异常：{}", e);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将字节数组转换为十六进制字符串
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];
        String s = new String(tempArr);
        return s;
    }

    public static void main(String[] args) {
        CheckRequestFromWeChatEntity entyty = new CheckRequestFromWeChatEntity();
        entyty.setSignature("18590da82b2fde8f870fd32b782c677917d397ad");
        entyty.setEchostr("8978197060654985959");
        entyty.setNonce("1530023844");
        entyty.setTimestamp("1522758247");
        boolean b = checkSignature(entyty);
        System.out.println(b);
    }

}
